<template>
    <view>
        <Skeleton v-if="skeletonShow" />
        <view v-else class="shop_container">
            <view class="search">
                <u-search
                    v-model.trim="state.keywords"
                    placeholder="输入自提点名称搜索自提点"
                    :clearabled="false"
                    :showAction="false"
                    @change="onSearch" />
            </view>

            <view class="shop_main" v-show="state.show">
                <scroll-view scroll-y="true" :scroll-top="state.scrollTop" class="shop_scroll" @scroll="onScroll">
                    <template v-if="!state.keywords">
                        <view class="shop_type_title">当前自提点</view>
                        <view v-if="!currentSiteInfo.siteId" class="lose"> 当前自提点已失效 </view>
                        <view v-else class="shop_card mb_0" @click="onSelectedSite(currentSiteInfo)">
                            <view class="info">
                                <view class="shop_name">{{ currentSiteInfo.siteName }}</view>
                                <view v-if="isNumber(currentSiteInfo.distance)" class="distance">{{
                                    getDistance(currentSiteInfo.distance)
                                }}</view>
                            </view>
                            <view class="position">
                                <view class="address">{{ getAddress(currentSiteInfo) }}</view>
                                <view class="icon_box" @tap.stop="onPosition(currentSiteInfo)">
                                    <image class="dingwei_icon" src="/static/marker/dingwei.png" />
                                </view>
                            </view>
                            <view class="phone">
                                <view class="tel">营业时间: {{ getSiteInfo(currentSiteInfo.siteInfo) }}</view>
                                <view class="icon_box" @tap.stop="onTel(currentSiteInfo.contactMobile)">
                                    <image class="dianhua_icon" src="/static/marker/dianhua.png" />
                                </view>
                            </view>
                        </view>
                        <view v-if="state.list.length" class="shop_type_title">其他自提点</view>
                    </template>
                    <view class="shop_card" v-for="item in state.list" :key="item.siteId" @click="onSelectedSite(item)">
                        <view class="info">
                            <view class="shop_name">
                                <text v-for="(it, i) in item.strArr" :key="`k${i}`" :style="{ color: it.color }">{{
                                    it.text
                                }}</text>
                            </view>
                            <view v-if="isNumber(item.distance)" class="distance">{{
                                getDistance(item.distance)
                            }}</view>
                        </view>
                        <view class="position">
                            <view class="address">{{ getAddress(item) }}</view>
                            <view class="icon_box" @tap.stop="onPosition(item)">
                                <image class="dingwei_icon" src="/static/marker/dingwei.png" />
                            </view>
                        </view>
                        <view class="phone">
                            <view class="tel">营业时间: {{ getSiteInfo(item.siteInfo) }}</view>
                            <view class="icon_box" @tap.stop="onTel(item.contactMobile)">
                                <image class="dianhua_icon" src="/static/marker/dianhua.png" />
                            </view>
                        </view>
                    </view>
                </scroll-view>
            </view>
            <view :style="{ paddingTop: state.show ? 0 : '300rpx' }">
                <u-loading-icon :show="!state.show" />
            </view>
            <Empty v-if="state.show && !state.list.length" mode="未搜索到相关自提点" />
        </view>
        <!-- 隐私监听 -->
        <el-privacy-listener-popup :key="12345"></el-privacy-listener-popup>
    </view>
</template>

<script setup>
import Skeleton from './skeleton.vue';
import Empty from '@/components/empty';
import request from '@/request';
import router from '@/router';
import store from '@/store';
import { getHighlightStrArray, isObject, isNumber } from '@/commons/utils';
import { debounce } from 'lodash';
import { onShow } from '@dcloudio/uni-app';
import { nextTick, reactive, ref, watch, onMounted } from 'vue';

const props = defineProps({
    siteId: { type: String }
});
const skeletonShow = ref(true);
const goodsStore = store.useGoodsStore();
const state = reactive({
    keywords: '',
    scrollTop: 0,
    oldScrollTop: 0,
    show: true,
    list: []
});

/* 当前店铺 */
const currentSiteInfo = reactive({
    siteId: '',
    siteName: '',
    tel: '',
    distance: '',
    siteInfo: '',
    contactMobile: ''
});
const onScroll = e => {
    state.oldScrollTop = e.detail.scrollTop;
};
/* 回到顶部 */
const onGoTop = () => {
    state.scrollTop = state.oldScrollTop;
    nextTick(() => {
        state.scrollTop = 0;
    });
};

/* 获取距离 */
const getDistance = v => {
    if (v > 1000) {
        return `距您${(v / 1000).toFixed(1)}km`;
    }
    return `距您${v}m`;
};

const getAddress = item => {
    item.provinceName = item.provinceName === item.cityName ? '' : item.provinceName;
    const shengshiqv = item.provinceName + item.cityName + item.areaName;
    return `${shengshiqv}${item.streetName || item.address}`;
};
/* 获取营业时间 */
const getSiteInfo = arr => {
    const weeks = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    let activityText = '';
    if (Array.isArray(arr)) {
        const hasWeek = arr.map(item => weeks[item.weekTime - 1]);
        activityText = weeks
            .reduce(
                (prev, curr, currentIndex) => {
                    if (currentIndex == prev.total && hasWeek.find(item => item == curr)) {
                        prev.weeks[prev.arrI] = prev.weeks[prev.arrI] || [];
                        prev.weeks[prev.arrI].push(curr);
                    } else {
                        prev.arrI = prev.weeks.length;
                    }
                    prev.total = prev.total + 1;
                    return prev;
                },
                {
                    total: 0,
                    arrI: 0,
                    weeks: []
                }
            )
            ?.weeks?.map(item => {
                if (item.length > 2) {
                    return `${item[0]}至${item[item.length - 1]}`;
                }
                return item.join('、');
            })
            ?.join('、');
        activityText += ` ${arr[0].timeSegmentStart}~${arr[0].timeSegmentEnd}`;
        return activityText;
    }
};

/* 选择自提点 */
const onSelectedSite = async item => {
    goodsStore.siteId = item.siteId;
    goodsStore.siteObj = item;
    router.back();
};
/* 定位 */
const onPosition = item => {
    uni.openLocation({
        latitude: +item.lat,
        longitude: +item.lng,
        scale: 18,
        name: item.siteName,
        address: getAddress(item)
    });
};
/* 拨打电话 */
const onTel = phoneNumber => {
    uni.makePhoneCall({ phoneNumber });
};

/* 筛选关键字 */
const onKeyWord = siteList => {
    state.list = siteList.map(item => {
        item.strArr = getHighlightStrArray(item.siteName, state.keywords);
        return item;
    });
    onGoTop();
    state.show = true;
};

/* 获取自提点列表 */
const getSiteList = async () => {
    let params = { keywords: state.keywords, lng: '', lat: '', page: 1, perPage: 100 };
    uni.getLocation({
        type: 'gcj02',
        success: res => {
            params.lng = res.longitude;
            params.lat = res.latitude;
        },
        complete: async () => {
            try {
                state.show = false;
                const { data } = await request('getSiteListServ', params);
                skeletonShow.value = false;
                let siteList = Array.isArray(data.list) ? data.list : [];
                state.list = siteList.filter(item => {
                    if (item.siteId == props.siteId) {
                        Object.assign(currentSiteInfo, item);
                    }
                    return item.siteId != props.siteId;
                });
                if (state.keywords) currentSiteInfo.siteId = '';
                onKeyWord(state.keywords ? siteList : state.list);
            } catch (error) {
                skeletonShow.value = false;
                if (isObject(error)) {
                    uni.showToast({
                        title: error.data.msg,
                        icon: 'none',
                        duration: 3000
                    });
                }
            }
        }
    });
};

/* 搜索 */
const onSearch = debounce(async () => {
    getSiteList();
}, 400);
watch(
    () => state.keywords,
    () => {
        state.show = false;
    }
);

onMounted(() => {
    getSiteList();
});
</script>

<style lang="scss" scoped>
.shop_container {
    .search {
        position: fixed;
        top: 0;
        left: 0;
        z-index: 10;
        width: 100%;
        padding: 16rpx 29rpx 20rpx;
        border-top: 1rpx solid #f5f5f5;
        box-sizing: border-box;
        background-color: #fff;
    }
    .shop_main {
        padding: 96rpx 29rpx 0;
        height: 100%;
    }
    .shop_scroll {
        max-height: calc(100vh - 100rpx);
    }
    .shop_type_title {
        padding: 29rpx;
        font-size: 29rpx;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #33302d;
    }
    .lose {
        display: flex;
        align-items: center;
        height: 128rpx;
        padding: 28rpx;
        border-radius: 14rpx;
        background-color: #fff;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #969696;
        font-size: 25rpx;
    }
    .shop_card {
        padding: 28rpx 0 0 28rpx;
        margin-bottom: 18rpx;
        border-radius: 14rpx;
        background-color: #fff;
        &:first-child {
            margin-top: 18rpx;
        }
        .info {
            display: flex;
            .shop_name {
                flex: 1;
                font-size: 29rpx;
                font-family: PingFangSC-Medium, PingFang SC;
                font-weight: 500;
                color: #33302d;
                word-break: break-all;
            }
            .distance {
                margin-left: 42rpx;
                padding-right: 28rpx;
                font-size: 25rpx;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #33302d;
            }
        }
        .position {
            display: flex;
            .dingwei_icon {
                width: 29rpx;
                height: 29rpx;
                padding: 24rpx 29rpx 12rpx 10rpx;
            }
            .address {
                flex: 1;
                padding-top: 24rpx;
                font-size: 25rpx;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #969696;
                line-height: 36rpx;
                word-break: break-all;
            }
        }
        .phone {
            display: flex;
            .dianhua_icon {
                width: 29rpx;
                height: 29rpx;
                padding: 12rpx 29rpx 29rpx 10rpx;
            }
            .tel {
                flex: 1;
                padding-top: 12rpx;
                padding-bottom: 28rpx;
                font-size: 25rpx;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #969696;
            }
        }
    }
    .mb_0 {
        margin-bottom: 0;
    }
}
</style>
